import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/widgets/tagView/kq_number_tag_view.dart';

import '../../theme/kq_theme_manager.dart';

///有选择顺序的gridview
class KqSelectionOrderGridView<T extends ISelectionOrderGridViewItemData>
    extends StatefulWidget {
  /// 选中的颜色
  final Color? selectedColor;

  /// 未选中时的颜色
  final Color unselectedColor;

  /// 选中的字体颜色
  final Color selectedTextColor;

  /// 未选中时的字体颜色
  final Color unselectedTextColor;

  ///显示列数
  final int crossAxisCount;

  ///item的高度是根据item的宽度的比例来计算的，当item宽度小的时候，要调高该值保证item的高度
  final double childAspectRatio;

  ///需要显示的数据
  final List<T>? items;

  /// 选择点击时的回调，已排好序
  final Function(List<T>? datas)? onTap;

  const KqSelectionOrderGridView({
    super.key,
    this.selectedColor,
    this.unselectedColor = const Color(0xFFF5F5F5),
    this.crossAxisCount = 4,
    this.items,
    this.onTap,
    this.childAspectRatio = 2,
    this.selectedTextColor = const Color(0xFFFFFFFF),
    this.unselectedTextColor = const Color(0xFF595959),
  });

  @override
  State<StatefulWidget> createState() => _KqSelectionOrderGridViewState<T>();
}

class _KqSelectionOrderGridViewState<T extends ISelectionOrderGridViewItemData>
    extends State<KqSelectionOrderGridView<T>> {
  List<T> selectedData = [];

  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  void didUpdateWidget(covariant KqSelectionOrderGridView<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    init();
  }

  init() {
    selectedData.clear();
    if (widget.items.isNotNullOrEmpty) {
      for (T data in widget.items!) {
        if (data.isSelected) {
          selectedData.add(data);
        }
      }
    }
    selectedData.sort((a, b) {
      if (a.index == null || b.index == null) {
        return 0;
      }
      return a.index!.compareTo(b.index!);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      ///Container跟随GridView内容变化高度, shrinkWrap:true;
      shrinkWrap: true,

      ///取消滚动效果physics: NeverScrollableScrollPhysics();
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      crossAxisCount: widget.crossAxisCount,
      childAspectRatio: widget.childAspectRatio,
      mainAxisSpacing: 8.r,
      crossAxisSpacing: 8.r,
      children: getItems(),
    );
  }

  List<Widget> getItems() {
    List<Widget> list = [];
    if (widget.items.isNotNullOrEmpty) {
      for (T data in widget.items!) {
        list.add(
          Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                top: 8.r,
                right: 8.r,
                bottom: 0.r,
                left: 0.r,
                child: KqInkWell(
                  backgroundColor: data.isSelected
                      ? widget.selectedColor ??
                          KqThemeManager.getCommonConfig().mainColor ??
                          const Color(0xFF3A559B)
                      : widget.unselectedColor,
                  radius: 2.r,
                  onTap: () {
                    clearGroupSelected(data);
                    data.isSelected = !data.isSelected;
                    if (data.isSelected) {
                      if (!selectedData.contains(data)) {
                        selectedData.add(data);
                      }
                    } else {
                      if (selectedData.contains(data)) {
                        selectedData.remove(data);
                      }
                    }
                    sort();
                    widget.onTap?.call(selectedData);
                    setState(() {});
                  },
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(left: 12.r, right: 12.r),
                    child: Text(
                      data.title,
                      maxLines: 2,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: data.isSelected
                            ? widget.selectedTextColor
                            : widget.unselectedTextColor,
                        fontSize: KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .contentFontSize ??
                            12.sp,
                        fontWeight: FontWeight.normal,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: Visibility(
                  visible: data.index != null && data.isSelected,
                  child: KqNumberTagView(
                    number: data.index ?? 0,
                    minSize: 16.r,
                    backgroundColor: const Color(0xFFFF9F0A),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }
    return list;
  }

  ///清除分组其它已选择的选项
  clearGroupSelected(T opData) {
    selectedData.removeWhere((data) {
      if (opData.group != null &&
          opData != data &&
          data.group == opData.group &&
          data.isSelected) {
        data.isSelected = false;
        return true;
      }
      return false;
    });
  }

  ///排序
  sort() {
    for (int i = 0; i < selectedData.length; i++) {
      selectedData[i].index = i + 1;
    }
  }
}

class ISelectionOrderGridViewItemData {
  ///显示文本
  @JsonKey(includeToJson: false, includeFromJson: false)
  String title;

  /// 是否选中
  @JsonKey(includeToJson: false, includeFromJson: false)
  bool isSelected;

  /// 选中的index
  @JsonKey(includeToJson: false, includeFromJson: false)
  int? index;

  /// 分组，相同分组只能选择一个
  @JsonKey(includeToJson: false, includeFromJson: false)
  int? group;

  ISelectionOrderGridViewItemData(
    this.title, {
    this.isSelected = false,
    this.index,
    this.group,
  });
}
